package bandi.osgi.dalservice;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.util.tracker.ServiceTracker;

import bandi.osgi.dal.dao.devices.DeviceDAO;
import bandi.osgi.dal.dao.devicetypes.DeviceTypeDAO;
import bandi.osgi.dal.dao.users.UsersDAO;
import bandi.osgi.dalservice.service.DALService;
import bandi.osgi.dalservice.service.impl.DALServiceImpl;

/**
 * @author Bandi
 *
 */
public class DALServiceActivator implements BundleActivator {
	private ServiceReference myServiceReference;
	private ServiceRegistration myServiceRegistration;
	private DALServiceImpl dsi;
	private ServiceTracker finderTracker1, finderTracker2, finderTracker3;


	public void start(BundleContext context) throws Exception {
		String name = context.getBundle().getSymbolicName();
		System.out.println("\tBundle " + name + " starting:");
		System.out.println("\t\tAquireing services..");
		DeviceDAO dd = null;
		DeviceTypeDAO dtd = null;
		UsersDAO ud = null;
		try {
			do {
				System.out.println("\t\t\tWaiting for services...");
				finderTracker1 = new ServiceTracker(context, DeviceDAO.class
						.getName(), null);
				finderTracker1.open();
				dd = (DeviceDAO) finderTracker1.getService();
				if (dd == null) {
					dd = (DeviceDAO) finderTracker1.waitForService(10000);
				}
				finderTracker2 = new ServiceTracker(context,
						DeviceTypeDAO.class.getName(), null);
				finderTracker2.open();
				dtd = (DeviceTypeDAO) finderTracker2.getService();
				finderTracker3 = new ServiceTracker(context, UsersDAO.class
						.getName(), null);
				finderTracker3.open();
				ud = (UsersDAO) finderTracker3.getService();
			} while (dd == null || dtd == null || ud == null);

		} catch (Exception e) {
			System.err.println("ERROR(" + name
					+ "): could not aquire services! Message: "
					+ e.getMessage());
		}
		dsi = new DALServiceImpl(dd, dtd, ud);
		System.out.println("\t\tRegistering service object...");
		try {
			myServiceRegistration = context.registerService(DALService.class
					.getName(), dsi, null);
			System.out.println("\t\tService object registered.\n\tBundle "
					+ name + " is active.");
		} catch (Exception e) {
			System.out.println("ERROR(" + name
					+ "): could not register service objects! Message: "
					+ e.getMessage());
		}
	}
	
	public void stop(BundleContext context) throws Exception {
		String name = context.getBundle().getSymbolicName();
		myServiceRegistration.unregister();
		finderTracker1.close();
		finderTracker2.close();
		finderTracker3.close();
		System.out.println("\tBundle "+name+" has unregistered its services.");
	}

}
